<?php


namespace Hilaoyu\LaravelExtend\Services\Auth;


use Hilaoyu\LaravelPrivateApi\PrivateApiClient;

class AuthApiClient extends PrivateApiClient
{
    protected $client_config = [];

    public function __construct($client_config)
    {
        $this->client_config = $client_config;
        $uri = data_get($client_config, 'service_uri');
        $secret = data_get($client_config, 'secret');
        $app_id = data_get($client_config, 'app_id');

        parent::__construct($uri, $secret, $app_id);
    }

    public function register(array $data)
    {
        if ($this->request(data_get($this->client_config, 'paths.register'), $data)) {
            return $this->getResult('data');
        }
        $this->setError($this->getResult("message"), 'message');
        return false;
    }

    public function login(string $login_type, array $params, $guard_key = '')
    {
        $data = null;
        $user = null;
        $params['login_type'] = trim($login_type);
        if ($this->request(data_get($this->client_config, 'paths.login'), $params)) {
            $data = $this->getResult('data');
        }

        if ($data && ($account = data_get($data, 'account'))) {
            $user_id = '';
            if ($user = AuthService::LoadUser(['account' => $account], $guard_key)) {
                $user_id = data_get($data, 'id', '');
                $data = collect($data)->only([
                    'password',
                    'mobile',
                    'email',
                    //'sex',
                    //'date_of_birth',
                ])->toArray();
            }
            $user = AuthService::SaveUser($data,$user_id, $guard_key, false);


        }
        return $user;
    }

    public function userGet(array $credentials)
    {
        if ($this->request(data_get($this->client_config, 'paths.userGet'), $credentials)) {
            return $this->getResult('data');
        }
        return null;
    }

    public function userUpdate(array $credentials, array $data)
    {
        $params = [
            'credentials' => $credentials,
            'data' => $data,
        ];
        if ($this->request(data_get($this->client_config, 'paths.userUpdate'), $params)) {
            return $this->getResult('data');
        }
        return null;
    }

    public function changePassword($id, $old_password, $password)
    {
        $params = [
            'user_id' => $id,
            'old_password' => $old_password,
            'password' => $password,
        ];
        if ($this->request(data_get($this->client_config, 'paths.changePassword'), $params)) {
            return $this->getResult('data');
        }
        return null;
    }
}